package learn.mqtt.service.impl;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Throwables;
import learn.mqtt.MqttEmm;
import learn.mqtt.service.ProviderService;
import org.eclipse.paho.client.mqttv3.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

@Service
public class ProviderServiceImpl implements ProviderService {

    @Resource
    private MqttClient mqttClient;

    public String provider() {

        Map<String, String> messageMap = new HashMap<>();
        messageMap.put("message", "asd");
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
        String currentTimeString = now.format(formatter);
        messageMap.put("time", currentTimeString);
        String message = JSON.toJSONString(messageMap);

        MqttMessage mqttMessage = new MqttMessage();
        mqttMessage.setQos(0);
        mqttMessage.setPayload(message.getBytes(StandardCharsets.UTF_8));

        MqttTopic topic = mqttClient.getTopic(MqttEmm.DEMO_SPRINGBOOT.getTopIcName());
        try {
            MqttDeliveryToken publish = topic.publish(mqttMessage);
            publish.waitForCompletion();
        } catch (MqttException e) {
            System.out.println(Throwables.getStackTraceAsString(e));

        }
        return "OK";
    }

}
